﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using SiteServer.Plugin;
using Thingpower.SS.EduOnline.Model;

namespace Thingpower.SS.EduOnline.Provider
{
    public class CoursewareDAO : BaseDAO
    {
        public const string TableName = "courseware_Content";

        public static int GetCount(string queryExpression)
        {
            string sqlString =
                $"SELECT COUNT(*) FROM {TableName} WHERE {queryExpression}";

            return int.Parse(DataApi.ExecuteScalar(ConnectionString, sqlString).ToString());

        }

        public static List<Courseware> GetModelList(string queryExpression)
        {
            var list = new List<Courseware>();
            string sqlString = $"SELECT Id, Title, ImageUrl, SiteId, ChannelId FROM {TableName} WHERE {queryExpression}";

            using (var rdr = DataApi.ExecuteReader(ConnectionString, sqlString))
            {
                while (rdr.Read())
                {
                    list.Add(GetModel(rdr));
                }
                rdr.Close();
            }

            return list;
        }

        private static Courseware GetModel(IDataRecord rdr)
        {
            if (rdr == null) return null;

            var _model = new Courseware();

            var i = 0;
            _model.Id = rdr.IsDBNull(i) ? 0 : rdr.GetInt32(i);
            i++;
            _model.Title = rdr.IsDBNull(i) ? string.Empty : rdr.GetString(i);
            i++;
            _model.ImageUrl = rdr.IsDBNull(i) ? string.Empty : rdr.GetString(i).Substring(1);
            i++;
            _model.SiteId = rdr.IsDBNull(i) ? 0 : rdr.GetInt32(i);
            i++;
            _model.ChannelId = rdr.IsDBNull(i) ? 0 : rdr.GetInt32(i);

            return _model;
        }

    }
}